const computedBehavior = require("miniprogram-computed").behavior;
Component({
  behaviors: [computedBehavior],
  data: {
    cartList: [],
  },
  methods: {
    //提交订单
    handleSubmit() {
      // 过滤
      let trueCart = this.data.cartList.filter((item) => {
        return item.checked;
      });
      if (trueCart.length == 0) {
        return wx.showToast({
          title: "还没选择商品",
          icon: "error",
        });
      }
      wx.setStorageSync("newcart", trueCart);
      wx.navigateTo({
        url: "/pages/orderlist/orderlist?sum=" + this.data.sum,
      });
    },
    onShow() {
      this.setData({
        cartList: wx.getStorageSync("cart") || [],
      });
    },
    // 单选状态
    oneChecked(e) {
      let { index } = e.currentTarget.dataset;
      this.data.cartList[index].checked = !this.data.cartList[index].checked;
      wx.setStorageSync("cart", this.data.cartList);
      this.setData({
        cartList: this.data.cartList,
      });
    },
    // 数量加减
    countChange(e) {
      // console.log(e);
      let { index } = e.currentTarget.dataset;
      this.data.cartList[index].count = e.detail;
      this.setData({
        cartList: this.data.cartList,
      });
      wx.setStorageSync("cart", this.data.cartList);
    },
    // 删除单个
    oneDel(e) {
      let { index } = e.currentTarget.dataset;
      // 询问框
      wx.showModal({
        title: "确定要删除嘛？",
        success: (res) => {
          this.data.cartList.splice(index, 1);
          this.setData({
            cartList: this.data.cartList,
          });
          wx.setStorageSync("cart", this.data.cartList);
        },
      });
    },
    // 全选
    all() {
      let flag = !this.data.allChecked;
      this.data.cartList.forEach((item) => {
        item.checked = flag;
      });
      this.setData({
        cartList: this.data.cartList,
      });
    },
  },
  computed: {
    // 全选
    allChecked(data) {
      if (data.cartList.length == 0) return false;
      return data.cartList.every((item) => {
        return item.checked;
      });
    },
    // 总价
    sum(data) {
      return data.cartList.reduce((total, item) => {
        if (item.checked) {
          return (total += item.count * item.minPrice);
        }
        return total;
      }, 0);
    },
  },
});
